package com.example.webmodule.strategy;

import com.alibaba.fastjson2.JSON;
import com.example.webmodule.entity.ServiceInfo;
import com.example.webmodule.util.HostnameToIpUtil;
import okhttp3.OkHttpClient;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;

import java.util.ArrayList;
import java.util.List;

public class EurekaRegistryStrategy extends AbstractWebRegistryStrategy implements RegistrySelectStrategy {

    private DiscoveryClient discoveryClient;

    public EurekaRegistryStrategy(DiscoveryClient discoveryClient, OkHttpClient okHttpClient) {
        super(okHttpClient);
        this.discoveryClient = discoveryClient;
    }

    @Override
    public void init() {

    }

    @Override
    public List<String> getServices()  {
        return discoveryClient.getServices();
    }

    @Override
    public List<ServiceInfo> getServiceInstances(String serviceId) throws Exception {
        List<ServiceInstance> instanceList = discoveryClient.getInstances(serviceId);
        List<ServiceInfo> result = new ArrayList<>();
        for (ServiceInstance instance: instanceList) {
            ServiceInfo serviceInfo = ServiceInfo.builder()
                    .ip(HostnameToIpUtil.convertToIp(instance.getHost()))
                    .port(String.valueOf(instance.getPort()))
                    .instanceId(instance.getInstanceId())
                    .build();
            serviceInfo.setMetadata(JSON.toJSONString(instance.getMetadata()));
            serviceInfo.setServiceId(instance.getServiceId());
            serviceInfo.setScheme(instance.getScheme());
            serviceInfo.setUri(instance.getUri().toString());
            result.add(serviceInfo);
        }
        return result;
    }

    @Override
    public void subscribe(String serviceName) {

    }
}
